using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

partial struct EnemySpawnerSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        EntityReferences entityReferences = SystemAPI.GetSingleton<EntityReferences>();
        EntityCommandBuffer entityCommandBuffer =
            SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged);
        Random random = new Random(1);
        foreach ((
            RefRO<LocalTransform> localTransform, 
            RefRW<EnemySpawner> enemySpawner) 
            in SystemAPI.Query<
                RefRO<LocalTransform>, 
                RefRW<EnemySpawner>>())
        {
            if(enemySpawner.ValueRO.amount > 1)
            {
                if(enemySpawner.ValueRO.finished)
                {
                    continue;
                }
                int rx;float2 dir;
                for(int i = 0;i < enemySpawner.ValueRO.amount;i++)
                {
                    dir = random.NextFloat2Direction();
                    rx = random.NextInt(50,800);
                    Entity _enemyEntity = state.EntityManager.Instantiate(entityReferences.enemyEntity);
                    SystemAPI.SetComponent(_enemyEntity, LocalTransform.FromPosition(localTransform.ValueRO.Position + new float3(rx * dir.x, 0, rx * dir.y)));
                }
                enemySpawner.ValueRW.finished = true;
                continue;
            }
            if(enemySpawner.ValueRO.timer > 0)
            {
                enemySpawner.ValueRW.timer -= SystemAPI.Time.DeltaTime;
                continue;
            }
            enemySpawner.ValueRW.timer = enemySpawner.ValueRO.timerMax;

            Entity enemyEntity = state.EntityManager.Instantiate(entityReferences.enemyEntity);
            SystemAPI.SetComponent(enemyEntity,LocalTransform.FromPosition(localTransform.ValueRO.Position));
        }
    }
}
